package com.cat.model.web.action.callback;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;

import com.cat.model.biz.logic.OrderLogic;
import com.cat.model.common.util.FileUtil;
import com.cat.model.common.util.WechatPayUtil;
import com.cat.model.common.util.XMLUtil;
import com.cat.model.common.util.XmlConverUtil;
import com.cat.model.web.action.base.BaseAction;


public class WechatMpNotifyAction extends BaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = -2748894053317050038L;
	
	@Autowired
	private OrderLogic orderLogic;

//	//商户号
//	String partner = Config.PARTNER;
//	//密钥
//	
//	public static final String APP_ID = Config.PAY_APP_ID;//第三方用户唯一凭证
//	public static final String APPSECRET = Config.PAY_APPSECRET;//第三方用户唯一凭证密钥
	
	//调试模式
	boolean DEBUG_ = true;
	
	public void doNotify() throws IOException{
		System.out.println("微信支付通知进入=========================");
		//---------------------------------------------------------
		//微信支付通知（后台通知）示例，商户按照此文档进行开发即可
		//---------------------------------------------------------
		InputStream is = request.getInputStream();
		String xmlStr = FileUtil.convertStreamToString(is);
//		String xmlStr = "<xml><appid><![CDATA[wxca54beea7349619e]]></appid>/n<bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1220687601]]></mch_id><nonce_str><![CDATA[1234567]]></nonce_str><openid><![CDATA[oQexAuPYOiyaD9NgtfYVBxuJnRiU]]></openid><out_trade_no><![CDATA[2015072090078381Z7040]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[63E8CF42A70D53ED8F2C8E0A824C85CB]]></sign><time_end><![CDATA[20150720235821]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1007420912201507200445587548]]></transaction_id></xml>";
		System.out.println("notifyParams:" + xmlStr);
		Map<String, String> map = null;
		try {
			map = XMLUtil.doXMLParse(xmlStr);
		} catch (JDOMException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String sign = (String)map.remove("sign");
		
		SortedMap<String, String> map2 = new TreeMap<String, String>();
		map2.putAll(map);
//		String sign2 = WechatPayUtil.createSign(map2);TODO暂时没有PARTNER_KEY
		
		//创建请求对象
//		if (sign2.equals(sign)) {
			if ("FAIL".equals(map.get("return_code"))) {
				//此处应该更新一下订单状态，商户自行增删操作
				
			}
			else if ("FAIL".equals(map.get("result_code"))) {
				//此处应该更新一下订单状态，商户自行增删操作
				
			}else{
				//商户订单号
				String out_trade_no = map.get("out_trade_no");
				//财付通订单号
				String transaction_id = map.get("transaction_id");
				//金额,以分为单位
				String total_fee = map.get("total_fee");
				//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
				String discount = map.get("discount");
				//支付结果
				String trade_state = map.get("trade_state");
				
				BigDecimal payAmount = new BigDecimal(total_fee).setScale(0, BigDecimal.ROUND_DOWN);

				//请在这里加上商户的业务逻辑程序代码
				String SPLIT_CHAR = "Z";
				if(out_trade_no.contains(SPLIT_CHAR)){
					int index = out_trade_no.lastIndexOf(SPLIT_CHAR);
					out_trade_no = out_trade_no.substring(0, index);
				}
				
				try {
					orderLogic.updateOrderSuccess(out_trade_no, "wxmp", transaction_id, payAmount);
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
			}
			
			Map<String, String> result = new HashMap<String, String>();
			result.put("return_code", "SUCCESS");
			System.out.println("处理成功");
			print(XmlConverUtil.maptoXml(result));
//		} else {
//			System.out.println("通知签名验证失败");
//			Map<String, String> result = new HashMap<String, String>();
//			result.put("return_code", "FAIL");
//			result.put("return_msg", "签名验证失败");
//			print(XmlConverUtil.maptoXml(result));
//		}
	}
	
	public static void main(String[] args) throws IOException{
//		String xmlStr = "<xml><appid><![CDATA[wxca54beea7349619e]]></appid>/n<bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1220687601]]></mch_id><nonce_str><![CDATA[1234567]]></nonce_str><openid><![CDATA[oQexAuPYOiyaD9NgtfYVBxuJnRiU]]></openid><out_trade_no><![CDATA[2015072090078381Z7040]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[63E8CF42A70D53ED8F2C8E0A824C85CB]]></sign><time_end><![CDATA[20150720235821]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1007420912201507200445587548]]></transaction_id></xml>";
//		Map<String, String> map = null;
//		try {
//			map = XMLUtil.doXMLParse(xmlStr);
//		} catch (JDOMException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		String sign = (String)map.remove("sign");
		
		WechatMpNotifyAction action = new WechatMpNotifyAction();
		action.doNotify();
	}
}
